package io.codescience.aianaly.utils;

public class FileParser {

    public static String parseFile(org.springframework.web.multipart.MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        if (filename == null) {
            throw new Exception("文件名不能为空");
        }
        if (filename.endsWith(".txt")) {
            return new String(file.getBytes());
        } else if (filename.endsWith(".pdf")) {
            return parsePdf(file);
        } else if (filename.endsWith(".docx")) {
            return parseDocx(file);
        } else {
            throw new Exception("不支持的文件格式: " + filename);
        }
    }

    private static String parsePdf(org.springframework.web.multipart.MultipartFile file) throws Exception {
        try (org.apache.pdfbox.pdmodel.PDDocument document = org.apache.pdfbox.pdmodel.PDDocument.load(file.getInputStream())) {
            org.apache.pdfbox.text.PDFTextStripper pdfStripper = new org.apache.pdfbox.text.PDFTextStripper();
            return pdfStripper.getText(document);
        }
    }

    private static String parseDocx(org.springframework.web.multipart.MultipartFile file) throws Exception {
        try (org.apache.poi.xwpf.usermodel.XWPFDocument document = new org.apache.poi.xwpf.usermodel.XWPFDocument(file.getInputStream())) {
            StringBuilder text = new StringBuilder();
            for (org.apache.poi.xwpf.usermodel.XWPFParagraph para : document.getParagraphs()) {
                text.append(para.getText()).append("\n");
            }
            return text.toString();
        }
    }
}
